package org.hroze.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.contrapunctus.lzma.LzmaInputStream;
import net.contrapunctus.lzma.LzmaOutputStream;

/**
 * Lzma 解压、压缩工具类
 * 
 * @author ahoo
 * @since 2010-09-21
 * @version 0.1
 * @email ahoo@hroze.com
 * @host hroze.org
 */
public class Lzma {
	/**
	 * lzma 压缩
	 * @param lzmaFile lzma 压缩文件
	 * @param file    被压缩文件
	 */
	public static void lzma(String file,String lzmaFile){
		lzma(new File(file),new File(lzmaFile));
	}
	/**
	 * lzma 压缩
	 * @param lzmaFile lzma 压缩文件
	 * @param file    被压缩文件
	 */
	public static void lzma(File file,File lzmaFile) {
		 LzmaOutputStream.LZMA_HEADER = true;
		 try {	//读取文件
			 	FileInputStream  fis = new FileInputStream(file);
				BufferedInputStream bis = new BufferedInputStream(fis);
				//输出压缩文件
			 	FileOutputStream  fos = new FileOutputStream(lzmaFile);
				LzmaOutputStream lo = new LzmaOutputStream( fos );
				BufferedOutputStream bos = new BufferedOutputStream(lo);

				int c;

				while ((c = bis.read()) != -1) {

					bos.write((byte) c);

				}

				bos.close();
				lo.close();
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
	/**
	 * lzma解压
	 * @param lzmaFile  lzma 压缩文件
	 * @param file     压缩后文件
	 */
	public static void unlzma(String lzmaFile,String file) {
		unlzma(new File(lzmaFile),new File(file));
	}
	/**
	 * lzma解压
	 * @param lzmaFile  lzma 压缩文件
	 * @param file     压缩后文件
	 */
	public static void unlzma(File lzmaFile,File file) {
        LzmaOutputStream.LZMA_HEADER = true;
        
		try {
			FileInputStream  fis = new FileInputStream(lzmaFile);
			LzmaInputStream li = new LzmaInputStream( fis );
			BufferedInputStream bis = new BufferedInputStream(li);
			FileOutputStream fos = new FileOutputStream(file);

			BufferedOutputStream bos = new BufferedOutputStream(fos);

			int c;

			while ((c = bis.read()) != -1) {

				bos.write((byte) c);

			}

			bos.close();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}
	public static void main(String[] args) {
		//压缩
		lzma("d:\\txt.txt","d:\\txt.txt.lzma");
		//解压
		unlzma("d:\\txt.txt.lzma","d:\\txt.txt.lzma.unlzma");
	}

}
